package com.ruoyi.binding.service.impl;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.binding.mapper.MhUpstreamStudioConfigMapper;
import com.ruoyi.binding.domain.MhUpstreamStudioConfig;
import com.ruoyi.binding.service.IMhUpstreamStudioConfigService;

/**
 * 上家地址配置Service业务层处理
 * 
 * @author Ekko
 * @date 2025-08-04
 */
@Service
@Slf4j
public class MhUpstreamStudioConfigServiceImpl implements IMhUpstreamStudioConfigService {
    @Autowired
    private MhUpstreamStudioConfigMapper mhUpstreamStudioConfigMapper;

    /**
     * 查询上家地址配置
     * 
     * @param id 上家地址配置主键
     * @return 上家地址配置
     */
    @Override
    public MhUpstreamStudioConfig selectMhUpstreamStudioConfigById(Long id) {
        return mhUpstreamStudioConfigMapper.selectMhUpstreamStudioConfigById(id);
    }

    /**
     * 查询上家地址配置列表
     * 
     * @param mhUpstreamStudioConfig 上家地址配置
     * @return 上家地址配置
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<MhUpstreamStudioConfig> selectMhUpstreamStudioConfigList(
            MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        return mhUpstreamStudioConfigMapper.selectMhUpstreamStudioConfigList(mhUpstreamStudioConfig);
    }

    @Override
    public List<MhUpstreamStudioConfig> selectConfigByDept(MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        return mhUpstreamStudioConfigMapper.selectConfigByDeptId( mhUpstreamStudioConfig);
    }

    /**
     * @param mhUpstreamStudioConfig
     * @return
     */
    @Override
    public List<MhUpstreamStudioConfig> selectMhUpstreamStudioConfigNoScopeList(MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        return mhUpstreamStudioConfigMapper.selectMhUpstreamStudioConfigNoScopeList(mhUpstreamStudioConfig);
    }

    //    验证上家地址是否可用
    private boolean verifyStudioUrl(MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        OkHttpClient client = new OkHttpClient();
        String json = "{\"acc\":\""+mhUpstreamStudioConfig.getUsername()+"\", \"pwd\":\""+mhUpstreamStudioConfig.getPassword()+"\"}";
        RequestBody body = RequestBody.create(
                json,
                MediaType.parse("application/json; charset=utf-8")
        );
        Request request = new Request.Builder()
                .url(mhUpstreamStudioConfig.getStudioUrl()+"/Login/Login") // 替换为你的接口地址
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (response.body() != null) {
                String responseBody = response.body().string();
                System.out.println("响应结果: " + responseBody);

                JSONObject jsonT = JSONObject.parseObject(responseBody);
                Integer code = jsonT.getInteger("code");
                String msg = jsonT.getString("msg");

                if (code != null && code == 1) {
                    log.info("上家账号验证成功");
                    // TODO: 登录成功后的逻辑
                    return true;
                } else {
                    log.error("登录失败: {}", msg);
                    throw new ServiceException("上家账号验证失败: " + msg);
                }
            }
        } catch (Exception e) {
            log.error("HTTP请求失败: ", e);
            throw new ServiceException(e.getMessage());
        }
        return false;
    }

    /**
     * 新增上家地址配置
     * 
     * @param mhUpstreamStudioConfig 上家地址配置
     * @return 结果
     */
    @Override
    public int insertMhUpstreamStudioConfig(MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        if(mhUpstreamStudioConfig.getStudioUrl() == null || mhUpstreamStudioConfig.getUsername() == null || mhUpstreamStudioConfig.getPassword() == null) {
            throw new ServiceException("上家地址、用户名或密码不能为空");
        }
        // 验证上家地址是否可用
        if (!verifyStudioUrl(mhUpstreamStudioConfig)) {
            throw new ServiceException("上家地址验证失败，请检查上家地址、用户名和密码是否正确");
        }
        return mhUpstreamStudioConfigMapper.insertMhUpstreamStudioConfig(mhUpstreamStudioConfig);
    }

    /**
     * 修改上家地址配置
     * 
     * @param mhUpstreamStudioConfig 上家地址配置
     * @return 结果
     */
    @Override
    public int updateMhUpstreamStudioConfig(MhUpstreamStudioConfig mhUpstreamStudioConfig) {
        if(mhUpstreamStudioConfig.getStudioUrl() == null || mhUpstreamStudioConfig.getUsername() == null || mhUpstreamStudioConfig.getPassword() == null) {
            throw new ServiceException("上家地址、用户名或密码不能为空");
        }
        // 验证上家地址是否可用
        if (!verifyStudioUrl(mhUpstreamStudioConfig)) {
            throw new ServiceException("上家地址验证失败，请检查上家地址、用户名和密码是否正确");
        }
        mhUpstreamStudioConfig.setUpdateTime(DateUtils.getNowDate());
        return mhUpstreamStudioConfigMapper.updateMhUpstreamStudioConfig(mhUpstreamStudioConfig);
    }

    /**
     * 批量删除上家地址配置
     * 
     * @param ids 需要删除的上家地址配置主键
     * @return 结果
     */
    @Override
    public int deleteMhUpstreamStudioConfigByIds(Long[] ids) {
        return mhUpstreamStudioConfigMapper.deleteMhUpstreamStudioConfigByIds(ids);
    }

    /**
     * 删除上家地址配置信息
     * 
     * @param id 上家地址配置主键
     * @return 结果
     */
    @Override
    public int deleteMhUpstreamStudioConfigById(Long id) {
        return mhUpstreamStudioConfigMapper.deleteMhUpstreamStudioConfigById(id);
    }
}
